<?php

namespace Home\Controller;

use Home\Service\WordpressSyncerService;


class UserController extends BaseController
{
    public function index()
    {
        $this->display();
    }

    public function login()
    {
        if (IS_POST && tpx_config_get('wordpress_syncer_enable')) {

            // 首先尝试本地登录，如果没有登录
            $username = I('post.username', '', 'trim');
            $password = I('post.password');

            $ret = WordpressSyncerService::login($username, $password, $logined_uid);

            if (true !== $ret) {
                $this->error($ret);
            }

            // 登录用户
            $_SESSION ['member_user_uid'] = $logined_uid;
            $redirect = I('session.login_redirect', U('User/profile'));
            if (isset($_SESSION['login_redirect'])) {
                unset($_SESSION['login_redirect']);
            }
            $this->success('', $redirect);

        }

        include './app/Home/Controller/Modules/UserLoginUsernamePassword.php';
    }

    public function register()
    {
        if (tpx_config_get('wordpress_syncer_enable')) {
            $this->error('Wordpress同步已开启，禁止注册');
        }
        include './app/Home/Controller/Modules/UserRegisterUsernamePassword.php';
    }

    public function logout()
    {
        unset ($_SESSION ['member_user_uid']);
    }

    public function changepwd()
    {
        if (tpx_config_get('wordpress_syncer_enable')) {
            $this->error('Wordpress同步已开启，禁止修改密码');
        }
        include './app/Home/Controller/Modules/UserChangepwd.php';
    }

    public function profile()
    {
        if (IS_POST) {
            $profile = array();
            $profile['realname'] = I('post.profile_realname', '', 'trim');
            $this->_am->update('profile', $profile);
            $this->success('OK');
        }
        $this->display();
    }

    public function load_profile()
    {
        $data = array();

        $data['username'] = $this->_am->get('user.username');
        $data['upload_space_space'] = byte_format(intval($this->_am->get('upload_space.space')));

        $one = D('MemberUpload')->table('__MEMBER_UPLOAD__ mu')->join('__DATA_FILES__ df ON df.id=mu.data_id')
            ->field('sum(df.filesize) as total')->where(array('mu.uid' => MEMBER_LOGINED_UID))->find();
        $upload_size_current = $one['total'];

        $data['upload_space_used'] = byte_format($upload_size_current);

        $data['profile_realname'] = $this->_am->get('profile.realname');

        $this->ajaxReturn(array(
            'status' => 1,
            'data' => $data
        ));
    }
}